package com.xujianlun.cpms.service.sys.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xujianlun.cpms.common.ResponseCode;
import com.xujianlun.cpms.dto.UserDto;
import com.xujianlun.cpms.dto.UserPassWordDto;
import com.xujianlun.cpms.entity.sys.Menu;
import com.xujianlun.cpms.entity.sys.User;
import com.xujianlun.cpms.exception.ServiceException;
import com.xujianlun.cpms.mapper.sys.RoleMapper;
import com.xujianlun.cpms.mapper.sys.RoleMenuMapper;
import com.xujianlun.cpms.mapper.sys.UserMapper;
import com.xujianlun.cpms.service.sys.IMenuService;
import com.xujianlun.cpms.service.sys.IUserService;
import com.xujianlun.cpms.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author xujianlun
 * @since 2022-11-14
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private static final Log LOG =Log.get();
    @Autowired
    private RoleMapper roleMapper;

    @Resource
    private  RoleMenuMapper roleMenuMapper;

    @Resource
    private UserMapper userMapper;
    @Resource
    private IMenuService menuService;

    @Resource
    private EmailServiceImpl emailService;
    @Override
    public UserDto login(UserDto userDto) {
        User one = getUserInfo(userDto);
        if (one !=null){
            BeanUtil.copyProperties(one,userDto,true);
            //设置token
            String token = TokenUtil.getToken(one.getId().toString(), one.getPassWord());
            userDto.setToken(token);

            String role = one.getRole();//ROLE_ADMIN
            Integer roleId = roleMapper.selectByMark(role);
            //设置用户的菜单列表74
            List<Menu> roleUserMenus = getRoleUserMenus(roleId);
            userDto.setMenu(roleUserMenus);
            return userDto;
        }else {
            throw new ServiceException(ResponseCode.USER_USERNAME_PASSWORD);
        }
    }

    @Override
    public User register(UserDto userDto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",userDto.getUserName());
        User one;//从数据库查询信息
        try {
            one = getOne(queryWrapper);//从数据库查询信息
        } catch (Exception e) {
            throw new ServiceException(ResponseCode.ERROR_CODE500);
        }
        User reOne = getUserInfo(userDto);
        if (one == null){
            reOne = new User();
            BeanUtil.copyProperties(userDto,reOne,true);
            save(reOne); //存入数据库
        } else {
            throw new ServiceException(ResponseCode.USER_EXIST);
        }
        return reOne;
    }

    /**
     * 输入密码修改密码
     * @param userPassWordDto
     */
    @Override
    public void updatePassword(UserPassWordDto userPassWordDto) {
        int update = userMapper.updatePassword(userPassWordDto);
        if (update < 1) {
            throw new ServiceException(600, "密码错误");
        }
    }

    @Override
    public String findPassWord(String email, String userName) {
        return null;
    }

    @Override
    public void updatePasswordByEmailUserName(String email, String passWord, String userName) {
        int i = userMapper.updatePasswordByEmailUserName(email, passWord, userName);
        if (i < 1){
            throw new ServiceException(600, "邮箱账号名出问题了，请重新尝试");
        }
    }

    /**
     * 查询学校的学生信息
     * @param userPage
     * @param nickName
     * @param phone
     * @param address
     * @param local
     * @return
     */
    @Override
    public Page<User> getSchoolPage(Page<User> userPage, String nickName, String phone, String address, String local,String localName) {
        return userMapper.getSchoolPage(userPage,nickName,phone,address,local,localName);
    }


    /**
     * 用户注册操作
     * @param userDto
     * @return
     */
    private User getUserInfo(UserDto userDto){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",userDto.getUserName());
        queryWrapper.eq("pass_word",userDto.getPassWord());
        User one;//从数据库查询信息
        try {
            one = getOne(queryWrapper);//从数据库查询信息
        } catch (Exception e) {
            throw new ServiceException(ResponseCode.ERROR_CODE500);
        }
        return one;
    }

    /**
     * 当前角色的菜单列表
     * @param roleId
     * @return
     */
    private List<Menu> getRoleUserMenus(Integer roleId){
        List<Integer> ids = roleMenuMapper.selectByRoleId(roleId);//根据role_id查出所有的menuid
        List<Menu> allMenus = menuService.findAllMenus("");//查出所有的菜单，
        //new 一个最后筛选的List
        List<Menu> roleMenus = new ArrayList<>();
//            筛选当前用户的菜单
        for (Menu menu : allMenus){
            if (ids.contains(menu.getId())){
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            //removeIf:移除children里面不在ids集合中的元素
            children.removeIf(child ->!ids.contains(child.getId()));
        }
        return roleMenus;
    }
}
